package org.filehanding.controller;

import org.filehanding.entity.User;
import org.filehanding.service.UserService;
import org.filehanding.validator.UserValidator;
import org.filehanding.vo.ResponseValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * Created by liguo on 2016/5/14.
 */
@RestController
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @InitBinder("user")
    public void initUserBinder(WebDataBinder dataBinder) {

        dataBinder.setValidator(new UserValidator());
    }

    /**
     * 用户注册
     *
     * @param user
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/user/add", method = RequestMethod.POST)
    @ResponseBody
    public ResponseValue add(@Valid User user, BindingResult bindingResult) {
        ResponseValue bindingCheck = constructCheckResponse(bindingResult);
        if (null != bindingCheck) {
            return bindingCheck;
        }
        return userService.addUser(user);

    }

    /**
     * 用户登录
     *
     * @param user
     * @param session
     * @return
     */
    @RequestMapping(value = "/user/login", method = RequestMethod.GET)
    @ResponseBody
    public ResponseValue userLogin(User user, HttpSession session) {
        User userInfo = userService.getUser(user);
        if (userInfo != null) {
            session.setAttribute("loginUser", userInfo);
            return constructSuccessDefaultResponse();
        } else {
            return constructNotAcceptResponse("用户名或密码错误，请重试！");

        }


    }
}
